import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { inventory, inventoryHistory } from '@/lib/schema';
import { eq } from 'drizzle-orm';

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    
    const { productId, adjustment, type, notes } = body;

    if (!productId || adjustment === undefined || !type) {
      return NextResponse.json(
        { error: '产品ID、调整数量和类型不能为空' },
        { status: 400 }
      );
    }

    if (adjustment <= 0) {
      return NextResponse.json(
        { error: '调整数量必须大于0' },
        { status: 400 }
      );
    }

    // 获取当前库存
    const currentInventory = await db
      .select()
      .from(inventory)
      .where(eq(inventory.productId, productId))
      .limit(1);

    if (currentInventory.length === 0) {
      return NextResponse.json(
        { error: '库存记录不存在' },
        { status: 404 }
      );
    }

    const currentQuantity = currentInventory[0].quantity;
    let newQuantity = currentQuantity;

    // 验证类型
    const validTypes = ['in', 'out', 'adjust', 'initial'];
    if (!validTypes.includes(type)) {
      return NextResponse.json(
        { error: '无效的调整类型' },
        { status: 400 }
      );
    }

    // 根据类型调整库存
    if (type === 'in') {
      newQuantity = currentQuantity + adjustment;
    } else if (type === 'out') {
      if (currentQuantity < adjustment) {
        return NextResponse.json(
          { error: '库存不足，无法出库' },
          { status: 400 }
        );
      }
      newQuantity = currentQuantity - adjustment;
    } else {
      // 对于 adjust 和 initial 类型，直接设置新数量
      newQuantity = adjustment;
    }

    // 更新库存
    const [updatedInventory] = await db
      .update(inventory)
      .set({
        quantity: newQuantity,
        updatedAt: new Date(),
      })
      .where(eq(inventory.productId, productId))
      .returning();

    // 记录库存变更历史
    await db
      .insert(inventoryHistory)
      .values({
        productId: productId,
        type: type,
        quantity: adjustment,
        previousQuantity: currentQuantity,
        newQuantity: newQuantity,
        notes: notes || `${type === 'in' ? '入库' : '出库'}调整`,
        createdBy: 'user',
      });
    
    return NextResponse.json({
      ...updatedInventory,
      adjustment: adjustment,
      adjustmentType: type,
      previousQuantity: currentQuantity,
      notes: notes
    });

  } catch (error: any) {
    console.error('调整库存失败:', error);
    
    return NextResponse.json(
      { error: '调整库存失败: ' + (error.message || '数据库错误') },
      { status: 500 }
    );
  }
}